package com.stenio.fancat.service.user;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stenio.fancat.domain.baby.BabyRelationship;
import com.stenio.fancat.domain.user.UserRelationship;
import com.stenio.fancat.domain.user.UserRelationshipFomId;
import com.stenio.fancat.domain.user.UserRelationshipName;
import com.stenio.fancat.exception.FanCatException;
import com.stenio.fancat.form.user.UserKinsfolkForm;
import com.stenio.fancat.mapper.baby.BabyAccountMapper;
import com.stenio.fancat.mapper.baby.BabyRelationshipMapper;
import com.stenio.fancat.mapper.user.*;
import com.stenio.fancat.service.wx.WxPushServiceQcl;
import com.stenio.fancat.util.DateUtil;
import com.stenio.fancat.util.RedisUtil;
import com.stenio.fancat.vo.BabyRelationshipVO;
import com.stenio.fancat.vo.UserRelationshipVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * baby关系信息类
 */
@Service
public class UserRelationshipService extends ServiceImpl<UserRelationshipMapper, UserRelationship> {

    @Autowired
    private UserRelationshipMapper userRelationshipMapper;

    @Autowired
    private UserRelationshipCandyMapper userRelationshipCandyMapper;

    @Autowired
    private BabyRelationshipMapper babyRelationshipMapper;

    @Autowired
    private BabyAccountMapper babyMapper;

    @Autowired
    private UserRelationshipLogMapper userRelationshipLogMapper;

    @Autowired
    private UserRelationshipNameMapper userRelationshipNameMapper;

    @Autowired
    private UserRelationshipFomIdMapper userRelationshipFomIdMapper;

    @Autowired
    private WxPushServiceQcl wxPushServiceQcl;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${key}")
    private String babyKey;

    @Value("${kinsfolkListInvite}")
    private String key;

    @Value("${listKey}")
    private String listKey;

    @Value("templateNewPerson")
    private String templateNewPerson;

    /**
     * 通用查询
     * 根据userId查询babyId  (走的是缓存 --- Redis)
     * @param userId
     * @return
     */
    public String selectBabyId(String userId){
        return babyRelationshipMapper.selectBabyByUid(userId).getBabyId();
    }

    /**
     * 邀请亲人 （和登录的逻辑一样）
     * @param userKinsfolkForm
     * @return
     */
    @Transactional
    public Integer inviteKinsfolk(UserKinsfolkForm userKinsfolkForm) throws FanCatException {
        if(null == userKinsfolkForm){
            throw new FanCatException("参数异常");
        }
        Integer number = 0;
        //先查询该baby对应的user关系  ----->  先查询有没有邀请过
        UserRelationship user = userRelationshipMapper.selectUserInfoById(userKinsfolkForm.getKinsfolkUserId());
        if (user.getBabyId() != null && user.getBabyId().length() != 0) {
            throw new FanCatException("已经和宝宝有关联了");
        }
        //查询babyId
        String babyId = this.selectBabyId(userKinsfolkForm.getUserId());
        //修改关系
        userRelationshipMapper.modifyRelationship(userKinsfolkForm.getKinsfolkUserId(),babyId,userKinsfolkForm.getRelationship(),userKinsfolkForm.getUserId());

        BabyRelationship baby = new BabyRelationship();
        baby.setBabyId(babyId);
        baby.setUserId(userKinsfolkForm.getKinsfolkUserId());
        Date date = new Date();
        baby.setUpdateTime(date);
        baby.setCreateTime(date);
        babyRelationshipMapper.insert(baby);

        //邀请成功后推送微信模板消息
        String userId = userKinsfolkForm.getUserId();
        UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(userId);
        String[] arr = new String[5];
        arr[0] = "有新成员加入啦";
        arr[1] = "亲人圈";
        arr[2] = DateUtil.format(date,"yyyy-MM-dd HH:mm:ss");
        UserRelationshipFomId userRelationshipFomId = userRelationshipFomIdMapper.selectFormIdByUid(userId);
        if(null != userRelationshipFomId){
            String formId = userRelationshipFomIdMapper.selectFormIdByUid(userId).getFormId();
            //推送通知
            wxPushServiceQcl.pushOneUser(userRelationship.getOpenId(),formId,"zT81v_RBlI92CY5fwQgKN_mU0dGA0-aPdqmUa5_2kYQ",arr);
            //修改这个formid的状态
            userRelationshipFomIdMapper.modifyFormIdByUid(userId,formId);
        }

        //操作Redis
        redisUtil.del(key+babyId,listKey+babyId);

        return number;
    }

    /**
     * 被邀请页面的API
     * @param userId
     * @return
     */
    public BabyRelationshipVO invitedPage(String userId) throws FanCatException {
        if(null == userId){
            throw new FanCatException("参数异常");
        }
        BabyRelationshipVO babyRelationshipVO = new BabyRelationshipVO();
        //查询baby存在的关系传给前端展示，已经有的不能再次选择
        String babyId = this.selectBabyId(userId);
        List<UserRelationship> userRelationshipList = userRelationshipMapper.selectRelationship(babyId);
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<userRelationshipList.size();i++){
            list.add(userRelationshipList.get(i).getRelationship());
        }
        List<UserRelationshipName> listnames = userRelationshipNameMapper.selectAllNames();
        babyRelationshipVO.setUserRelationshipName(listnames);

        babyRelationshipVO.setSelectedNames(list);
        return babyRelationshipVO;
    }

    /**
     * 查询邀请的亲人的列表的页面 --------包含baby的昵称（已邀请的亲人）
     * @param userId
     * @return
     */
    public Map<String,Object> inviteUserList(String userId) throws FanCatException {
        if(null == userId){
            throw new FanCatException("参数异常");
        }

        //判断Redis中是否含有key
        String babyId = this.selectBabyId(userId);
        if(null != redisUtil.get(key+babyId)){
            return (Map<String, Object>) redisUtil.get(key+babyId);
        }

        //创建map容器
        Map<String,Object> map = new HashMap<>();
        //封装babyName
        String babyName = babyMapper.selectByBid(babyRelationshipMapper.selectBabyByUid(userId).getBabyId()).getNickName();
        map.put("babyName",babyName);
        List<UserRelationship> list = userRelationshipMapper.selectList(userId);
        if(list.isEmpty()){
            throw new FanCatException("还没有邀请任何亲人");
        }
        //创建userVO容器
        List<UserRelationshipVO> voList = new ArrayList<>();
        for(int i = 0;i<list.size();i++){
            UserRelationshipVO userRelationshipVO = new UserRelationshipVO();
            UserRelationshipName userRelationshipName = new UserRelationshipName();
            userRelationshipName.setRelationship(list.get(i).getRelationship());
            String rname = userRelationshipNameMapper.selectOne(userRelationshipName).getRelationshipName();
            userRelationshipVO.setUserId(list.get(i).getUserId());
            userRelationshipVO.setRelationshipName(rname);
            userRelationshipVO.setName(list.get(i).getName());
            userRelationshipVO.setImage(list.get(i).getIcon());
            voList.add(userRelationshipVO);
            userRelationshipVO.setState(list.get(i).getState());//0,未领取 1,为已经领取
        }

        //封装已经邀请的亲人列表
        map.put("userList",voList);

        //存放Redis中
        redisUtil.set(key+babyId,map);

        return map;
    }

    /**
     * 领取糖果币（candy）  如果领完变成已领取
     * @param userId
     * @return
     */
    @Transactional
    public Integer getUserCandy(String userId,String inviteUserId) throws FanCatException {
        if(null == userId){
            throw new FanCatException("参数异常");
        }
        Integer number = 0;
        //查询babyId
        String babyId = this.selectBabyId(inviteUserId);
        Integer candyFir = babyMapper.selectByBid(babyId).getSurplusCandy();
        int a = userRelationshipLogMapper.modifyCandy(200,inviteUserId,candyFir);
        int d= userRelationshipCandyMapper.modifyCandy(200,inviteUserId);
        int g = babyMapper.modifyCandy(200,babyId);
        //修改领取candy的状态为1
        int j = userRelationshipMapper.modifyRelationshipState(userId,inviteUserId);

        //操作Redis
        redisUtil.del(babyKey+babyId,key+babyId,listKey+babyId);

        if(a>0 && d>0 && g>0 && j>0){
            number = 1;
        }
        return number;

    }

}
